/**
 * Created by John on 2016/4/17.
 */

$(document).ready (function(){
    refresh();
    productlist(1);
    Autocomplete();
    search();
    $('#newproducts').on('click',function(){
        window.location.href='add.html';
    })
});
//绑定产品列表
function productlist(topage){
    //将当前页码保存，为后面样式做准备
    sessionStorage.setItem("topage",topage);
    if($("input[name='conditions']:checked")){
        var condition=$("input[name='conditions']:checked").val();
    }
    if($("input[name='order']:checked")){
        var order=$("input[name='order']:checked").val();
    }
    productlistUrl="产品列表的接口名";
    productlistData={
        topage:topage,
        maincondition:sessionStorage.getItem("maincondition"),
        instock:sessionStorage.getItem("instock"),
        inputperson:sessionStorage.getItem("inputperson"),
        startprice:sessionStorage.getItem("startprice"),
        endprice:sessionStorage.getItem("endprice"),
        condition:condition,
        order:order
    };
    postAjax(productlist,productlistData,function(data){
        sessionStorage.setItem("");
        var ractive = new Ractive({
            el:'#procucts_content_div',
            template:'#procucts_content',
            data:{procuctData:data}
        });
            ractive.on("productEdit",function(event){
                var data_index=event.node.parentElement.parentElement.getAttribute('data-index');
                console.log(data_index);
                sessionStorage.setItem("data-inex",data_index);
                window.location.href='add.html?productid='+data_index;
        });
        pages(topage,maxpage);
    })
}
//search event
function search(){
    $("input[name='search_conditions']").on("blur",function(){
        conditionsession();
        setTimeout(productlist(1),500);
    });
    $("input[name='instock']").on("click", function () {
        conditionsession();
        setTimeout(productlist(1),500);
    });
    $("input[name='inputperson']").on("click", function () {
        conditionsession();
        setTimeout(productlist(1),500);
    });
    $("input[name='conditions']").on("click",function(){
        productlist(1)
    });
    $("input[name='order']").on("click",function(){
        productlist(1)
    });
}
//Autocomplete
function Autocomplete(){
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#maincondition" )
        // 当选择一个条目时不离开文本域
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).data( "ui-autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            minLength: 0,
            source: function( request, response ) {
                // 回到 autocomplete，但是提取最后的条目
                response( $.ui.autocomplete.filter(
                    availableTags, extractLast( request.term ) ) );
            },
            focus: function() {
                // 防止在获得焦点时插入值
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // 移除当前输入
                terms.pop();
                // 添加被选项
                terms.push( ui.item.value );
                // 添加占位符，在结尾添加逗号+空格
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
}
//分页
function pages(topage,maxpage){
 /*  var pageurl='/action/pages';
    var pagedata={
        maincondition:sessionStorage.getItem("maincondition"),
        instock:sessionStorage.getItem("instock"),
        inputperson:sessionStorage.getItem("inputperson"),
        startprice:sessionStorage.getItem("startprice"),
        endprice:sessionStorage.getItem("endprice")
    };
    postAjax(pageurl,pagedata,function(data){
       var sum=data.data.max;*/
        //var sum=sessionStorage.getItem("maxpages");
        var sum=maxpage;
        var pagestr="";
        var pas1='<li><a href="javascript:void(0);"  onclick=\"productlist(' +(index-1)+ ')\">'+ "┅" + '</a></li>';
        var pas4='<li><a href="javascript:void(0);" onclick=\"productlist(' +(sum-1)+ ')\">'+ "┅" + '</a></li>';
        var pas5='<li><a href="javascript:void(0);" onclick=\"productlist(' +(sum-5)+ ')\">'+ "┅" + '</a></li>';
        var pas2='<li><a href="javascript:void(0);" onclick=\"productlist(' + sum+ ')\">'+ sum + '</a></li>';
        var pas3='<li><a href="javascript:void(0);" onclick=\"productlist(' + 1+ ')\">'+1  + '</a></li>';
        var write=document.getElementById('pagenum');
        if(sum<=9){
            for(var i=1;i<=sum;i++)
            {
                pagestr+='<li><a href="javascript:void(0);" onclick=\"productlist(' + i+ ')\">'+ i + '</a></li>';
            }
            write.innerHTML=pagestr;
        } else{
            if(index==1||index==2||index==3){
                for(var k=1;k<=5;k++){
                    pagestr+='<li><a href="javascript:void(0);" onclick=\"productlist(' + k+ ')\">'+ k + '</a></li>';
                }
                pagestr+=pas4 +pas2;
                write.innerHTML=pagestr;
            }else{
                if(index>3){
                    pagestr=pas3 +pas1
                    +'<li><a href="javascript:void(0);" onclick=\"productlist(' + (index-1)+ ')\">'+(index-1)  + '</a></li>';
                    if(index+3<sum){
                        for(var j=0;j<3;index++,j++){
                            pagestr+='<li><a href="javascript:void(0);" onclick=\"productlist(' + index+ ')\">'+ index + '</a></li>';
                        }
                        pagestr+=(pas4 +pas2);
                        write.innerHTML=pagestr;
                    }else{
                        pagestr=pas3 +pas5
                        +'<li><a href="javascript:void(0);" onclick=\"productlist(' + (sum-4)+ ')\">'+(sum-4)  + '</a></li>';
                        for(var i=3;i>=0;i--){
                            pagestr+='<li><a href="javascript:void(0);" onclick=\"productlist(' + (sum-i)+ ')\">'+ (sum-i) + '</a></li>';
                        }
                        write.innerHTML=pagestr;
                    }
                }
            }
        }
        //var topage=sessionStorage.getItem("topage");
        var a_page= $("a[onclick='productlist("+topage+")']");
        a_page.addClass("page_a_style");

        if(index-1==0){
            document.getElementById('prev').style.visibility="hidden";
        } else{
            document.getElementById('prev').style.visibility="visible";
            document.getElementById('prev2').innerHTML="上一页";
        }
        if(index+1>sum){
            document.getElementById('next').style.visibility="hidden";
        } else{
            document.getElementById('next').style.visibility="visible";
            document.getElementById('next2').innerHTML="下一页";
        }
    //});
    document.getElementById('prev').onclick=function(){
        productlist(index-1)
    };
    document.getElementById('next').onclick=function(){
        productlist(index+1)
    };
}
//页面刷新清除session
function refresh(){
    //sessionStorage.removeItem("maxpages");
    sessionStorage.removeItem("maincondition");
    sessionStorage.removeItem("instock");
    sessionStorage.removeItem("inputperson");
    sessionStorage.removeItem("startprice");
    sessionStorage.removeItem("endprice");
}
//把搜索条件存成session
function conditionsession(){
    var maincondition=$("#maincondition").val;
    var inputperson=$("#inputperson");
    var startprice=$('#startprice').val();
    var endprice=$('#endprice').val();

    if($("input[name='instock']:checked")){
        sessionStorage.setItem("instock","true");
    }else{
        sessionStorage.setItem("instock","false");
    }
    if($("input[name='inputperson']:checked")){
        inputperson.val(sessionStorage.getItem("username"))
    }

    sessionStorage.setItem("maincondition",maincondition);
    sessionStorage.setItem("inputperson",inputperson.val());
    sessionStorage.setItem("startprice",startprice);
    sessionStorage.setItem("endprice",endprice);
}

window.onunload(function(){
    refresh();
});